<?php
/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean $adv 是否进行高级模式获取（有可能被伪装）
 * @return mixed
 */
function get_client_ip($type = 0,$adv=false) {
	$type       =  $type ? 1 : 0;
	static $ip  =   NULL;
	if ($ip !== NULL) return $ip[$type];
	if($adv){
		if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
			$arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
			$pos    =   array_search('unknown',$arr);
			if(false !== $pos) unset($arr[$pos]);
			$ip     =   trim($arr[0]);
		}elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
			$ip     =   $_SERVER['HTTP_CLIENT_IP'];
		}elseif (isset($_SERVER['REMOTE_ADDR'])) {
			$ip     =   $_SERVER['REMOTE_ADDR'];
		}
	}elseif (isset($_SERVER['REMOTE_ADDR'])) {
		$ip     =   $_SERVER['REMOTE_ADDR'];
	}
	// IP地址合法验证
	$long = sprintf("%u",ip2long($ip));
	$ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
	return $ip[$type];
}

//MD5加密盐值
function md5_salt($str,$salt='fycloud'){
	return md5(md5($str).$salt);
}


//生成随机字符串，ext决定是否需要后边的标点符号部分
function rand_str( $length = 16,$char=true,$num=true,$ext=false ) {
	// 密码字符集，可任意添加你需要的字符
	$chars='';
	if($char) $chars.='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
	if($num) $chars.='0123456789';
	if($ext) $chars.='!@#$%^&*()-_ []{}<>~`+=,.;:/?|';
	$rand_str = '';
	for ( $i = 0; $i < $length; $i++ ){
		// 这里提供两种字符获取方式
		// 第一种是使用 substr 截取$chars中的任意一位字符；
		// 第二种是取字符数组 $chars 的任意元素
		// $rand_str .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
		$rand_str .= $chars[ mt_rand(0, strlen($chars) - 1) ];
	}
	return $rand_str;
}

/**
 * @param $data 需要处理前缀的数组
 * @param $prefix   需要添加的前缀名称
 */
function procPrefix($data,$prefix='',$UntreatedPrefix=[]){
	$result=[];
	if($prefix==='') return $data;
	foreach($data as $key=>$value){
		//增加一个判断，如果前端传来的数据增加了前缀就不做处理，没有加前缀才做处理
		$str=strstr($key,$prefix);
		if ($str||in_array($key,$UntreatedPrefix)){
			$result[$key]=$value;
			continue;
		}
		$result["{$prefix}{$key}"]=$value;
	}
	return $result;
}

function formatTree($list, $lv = 0, $title = 'ma_name'){
	$formatTree = [];
	foreach($list as $key => $val){
		$title_prefix = '';
		for( $i=0;$i<$lv;$i++ ){
			$title_prefix .= "|---";
		}
		$val['lv'] = $lv;
		$val['namePrefix'] = $lv == 0 ? '' : $title_prefix;
		$val['showName'] = $lv == 0 ? $val[$title] : $title_prefix.$val[$title];
		if(!array_key_exists('children', $val)){
			array_push($formatTree, $val);
		}else{
			$child = $val['children'];
			unset($val['children']);
			array_push($formatTree, $val);
			$middle = formatTree($child, $lv+1, $title); //进行下一层递归
			$formatTree = array_merge($formatTree, $middle);
		}
	}
	return $formatTree;
}